package com.lj.infoisland.job.jobhandler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.lj.infoisland.domain.dto.HotSearchDetailDTO;
import com.lj.infoisland.domain.po.HotSearchRecord;
import com.lj.infoisland.service.HotSearchRecordService;
import com.lj.infoisland.util.HotSearchConvert;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

import static com.lj.infoisland.common.enums.HotSearchEnum.ZHIHU;
import static com.lj.infoisland.domain.cache.HotSearchCache.CACHE_MAP;


/*
 * @description 知乎热搜Java爬虫定时任务代码
 * @author 龙洁
 * @create 2024-10-22 下午2:29
 */
@Component
@Slf4j
public class ZhihuHotSearchJob {

    @Autowired
    private HotSearchRecordService hotSearchRecordService;

    @PostConstruct()
    public void init() {
        try {
            hotSearch(null);
            log.info("初始化知乎数据成功");
        } catch (Exception e) {
            log.error("初始化知乎数据异常", e);
        }
    }

    /**
     * 定时触发爬虫方法，1个小时执行一次
     */
    @XxlJob("zhihuHotSearchJob")
    public ReturnT<String> hotSearch(String param) {
        log.info("知乎热搜爬虫任务开始");
        try {
            //查询知乎热搜数据
            OkHttpClient client = new OkHttpClient().newBuilder().build();

            String cookie= "_zap=f274c039-2e5c-49df-a335-3680d83b0433; d_c0=APDWAlrQkxiPTs-qH-5saK7jx0pjmJVuj00=|1715016481; _xsrf=jbGTRdz60oDUtBHoMjf1n7jBomhMeO2U; __snaker__id=NjXWGOkLnVRqiSX0; q_c1=3916a0a4e11b4d1f94a451c6932e8426|1718027831000|1718027831000; __zse_ck=004_GDY=2E005UYgjPJUv6Smkz1W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QH//KwsMkpYMn4Ewiv1zsgnRYBL9UgjGFZDHOL0yps52zGPCEEF39vmp5A7nX5PGPy1P5O1bwYsOckvGfLWHHlUi9dw1qUCdqLWA=; captcha_session_v2=2|1:0|10:1747311347|18:captcha_session_v2|88:UUtBZ0ZHWlNIUEZGb2JPTU9OZWlmQk8wU0NWRjJzRU10dHl2dlh0eThzbkZZUnNqZ1VjRTJUSlhtWFdRNXI5Kw==|8e1ddc6b7d03b186c609589bcc20f51b026cdb5b7f4a4bc657fcccba3b68228c; captcha_ticket_v2=2|1:0|10:1747311355|17:captcha_ticket_v2|728:eyJ2YWxpZGF0ZSI6IkNOMzFfczVJZ1ZJSmF5bW9MRUw2WHBCbXk4ejlKWURlWmFjODEuaUw5VGVuNnIuNWx3emh2ajEuXzBiLkZXallSSEhEVHJDWDhyNS5sODBjeVp6Mk5oWEpybjAxZFR1UmFLQm94blljYWtFbGppQ2JNRDNQKmNGOWNEVWJqNGwyQlU5dFloaTZXZllUUmZySnA4WmJFSUd2S19iYkJ6S2xLWHVHemMxMVpxV192Sm81OEt5SUEuRUdrNEJTX2hwZVBIMlpRY2dqY3dQWm5yZ1owMFJSc2NmZjlfYnRiWi41UEtpZzNsMzkxRlBNd2Z0anhMWGxEaU1YOC5EMmhTYmFodUZQOU12TWdWQVMueWxjSmpUVVN5OHAxRXRScmJhZFBXVHFwV05fYW1UOW9NQzl6VmM5S0NuMUwueC50RnB5U3AqaXRpTXNxVHkxUU9KTDRSSmh1TnFCT0Rsakxnc2VLQV9wM2lla19zNlprT2dHUkdFbk1uMVFEU3lTNXhDZmhrQ3pvcFZQU05DQVBMVS5oNVlPT2cxSm53X0xFYXJUREx2d056RThUVkhXVWFHUlh0LnluMVZHMGdLOExkcDVKLjBuT3J5dWxhZE5Qbk1VVjVacGwuaVFOZzNTUmtHamJQcVpTclkxa2l2NXFucWNrc0kzOXRPaEVRS0E0YmRRMlI5OWYxXyoqQ1k3N192X2lfMSJ9|36596547912003a0f4fa55d2712827650352577d38dac8b58e275a9ea012dcdb; z_c0=2|1:0|10:1747311365|4:z_c0|92:Mi4xd3Q1NUtnQUFBQUFBOE5ZQ1d0Q1RHQ1lBQUFCZ0FsVk5CU2tUYVFEaVlwRmgzcW40a1N0QjRBdnJmV1NFZXFYWjJn|6ad92e64652e584ebd3bec4ba00361d16064e5fa9207e62980bf6549384b61a9; BEC=f7bc18b707cd87fca0d61511d015686f; tst=r; SESSIONID=Cf6goL1h40jEiG3k9dpkWJRuaqFErvBRh61YV6mNxYa";

            Request request = new Request.Builder().url("https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true")
                    .method("GET", null)
                    .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 ")
                    .addHeader("Authority","www.zhihu.com")
                    .addHeader("cookie",cookie).build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray array = jsonObject.getJSONArray("data");
            List<HotSearchRecord> hotSearchRecordList = Lists.newArrayList();
            for (int i = 0, len = array.size(); i < len; i++) {
                //获取知乎热搜信息
                JSONObject object = (JSONObject) array.get(i);
                JSONObject target = object.getJSONObject("target");
                //构建热搜信息榜
                HotSearchRecord hotSearchRecord = HotSearchRecord.builder().hotSearchResource(ZHIHU.getCode()).build();
                //设置知乎三方ID
                hotSearchRecord.setHotSearchId(target.getString("id"));
                //设置文章连接
                hotSearchRecord.setHotSearchUrl("https://www.zhihu.com/question/" + hotSearchRecord.getHotSearchId());
                //设置文章标题
                hotSearchRecord.setHotSearchTitle(target.getString("title"));
                //设置作者名称
                hotSearchRecord.setHotSearchAuthor(target.getJSONObject("author").getString("name"));
                //设置作者头像
                hotSearchRecord.setHotSearchAuthorAvatar(target.getJSONObject("author").getString("avatar_url"));
                //设置文章摘要
                hotSearchRecord.setHotSearchExcerpt(target.getString("excerpt"));
                //设置热搜热度
                hotSearchRecord.setHotSearchHeat(object.getString("detail_text").replace("热度", ""));
                //按顺序排名
                hotSearchRecord.setHotSearchOrder(i + 1);
                hotSearchRecordList.add(hotSearchRecord);
            }
            if (CollectionUtils.isEmpty(hotSearchRecordList)) {
                return ReturnT.SUCCESS;
            }
            //数据加到缓存中
            CACHE_MAP.put(ZHIHU.getCode(), HotSearchDetailDTO.builder()
                    //热搜数据
                    .hotSearchDTOList(
                            hotSearchRecordList.stream().map(HotSearchConvert::toDTOWhenQuery).collect(Collectors.toList()))
                    //更新时间
                    .updateTime(Calendar.getInstance().getTime()).build());
            //数据持久化
//            hotSearchRecordService.batchSave(hotSearchRecordList);
            log.info("知乎热搜爬虫任务结束");
            return ReturnT.SUCCESS;
        } catch (IOException e) {
            log.error("获取知乎数据异常", e);
        }
        return ReturnT.FAIL;
    }

}
